package cn.bon.security.handler;

import cn.bon.common.adapter.JsonSerializerAdapter;
import cn.bon.common.enums.ResultCode;
import cn.bon.common.tool.R;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AccessDeniedHandlerImpl  implements AccessDeniedHandler{
    @Resource
    JsonSerializerAdapter jsonSerializerAdapter;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        // 没有访问权限
        response.setContentType("application/json");
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(
                jsonSerializerAdapter.readObjectAsJson(
                        R.fail(ResultCode.NO_PERMISSION)
                )
        );
    }
}
